# 确保以管理员权限运行
function Test-Administrator
{
    $currentUser = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = New-Object Security.Principal.WindowsPrincipal($currentUser)
    $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}

if (-not (Test-Administrator))
{
    Start-Process powershell -ArgumentList "-ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs
    exit
}

# 定义阈值
$threshold = 100 * 1024 # 100kB/s
$monitorInterval = 5 # 5秒
$idleThreshold = 200 # 200秒

# 获取信号最强的Wi-Fi网络
function Get-StrongestWifiNetwork
{
    $networks = netsh wlan show networks mode=bssid | Select-String -Pattern "SSID|Signal"
    $ssid = ""
    $signalStrength = 0

    for ($i = 0; $i -lt $networks.Length; $i += 2) {
        $currentSSID = $networks[$i] -replace "SSID \d+ : ", ""
        $currentSignal = [int]($networks[$i + 1] -replace ".*: ", "").TrimEnd("%")

        if ($currentSignal -gt $signalStrength)
        {
            $ssid = $currentSSID
            $signalStrength = $currentSignal
        }
    }

    return $ssid
}

# 连接到指定的Wi-Fi网络
function Connect-ToWifi
{
    param (
        [string]$ssid
    )
    netsh wlan connect name=$ssid
    Write-Host "Connecting to Wi-Fi network: $ssid"
}

# 获取当前网速
function Get-NetworkSpeed
{
    $netAdapter = Get-NetAdapter | Where-Object { $_.Status -eq "Up" -and $_.NdisMedium -eq 802 }
    $statsStart = Get-NetAdapterStatistics -Name $netAdapter.Name

    Start-Sleep -Seconds $monitorInterval

    $statsEnd = Get-NetAdapterStatistics -Name $netAdapter.Name
    $bytesReceivedPerSecond = ($statsEnd.ReceivedBytes - $statsStart.ReceivedBytes) / $monitorInterval
    $bytesSentPerSecond = ($statsEnd.SentBytes - $statsStart.SentBytes) / $monitorInterval

    return [PSCustomObject]@{
        Received = $bytesReceivedPerSecond
        Sent = $bytesSentPerSecond
    }
}

# 主监测函数
function Monitor-Network
{
    $lastActiveTime = Get-Date

    while ($true)
    {
        $ssid = Get-StrongestWifiNetwork
        Connect-ToWifi -ssid $ssid
        Start-Sleep -Seconds 10 # 等待连接稳定

        while ($true)
        {
            $netSpeed = Get-NetworkSpeed
            $currentTime = Get-Date
            Write-Host "Current Wi-Fi: $ssid - Download Speed: $([math]::Round($netSpeed.Received / 1KB, 2) ) kB/s - Upload Speed: $([math]::Round($netSpeed.Sent / 1KB, 2) ) kB/s"

            if ($netSpeed.Received -gt $threshold -or $netSpeed.Sent -gt $threshold)
            {
                $lastActiveTime = $currentTime
            }

            if (($currentTime - $lastActiveTime).TotalSeconds -gt $idleThreshold)
            {
                break
            }
        }
    }
}

# 开始监测
Monitor-Network
